# coding=utf-8
import sys
import re
import requests
from PIL import Image, ImageDraw
import mkl
import pytesseract
from hashlib import md5
from urllib import request
from http import cookiejar
import json
import xlwt
import xlrd

# headers={
#    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0'
# }
# img_url = 'http://wgpc.wzsafety.gov.cn/ValidataImage.aspx'
# res = requests.get(img_url, headers=headers)
# img_data = res.content
# with open(r'E:/pythonsoft/yzm.jpg', mode='wb') as f:
#    f.write(img_data)


headers = {
    'Accept': '*/*',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
    'Connection': 'keep-alive',
    'Content-Length': '77',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'Host': 'wgpc.wzsafety.gov.cn',
    'Origin': 'http://wgpc.wzsafety.gov.cn',
    'Referer': 'http://wgpc.wzsafety.gov.cn/login_qygl.htm',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0',
    'X-Requested-With': 'XMLHttpRequest',
    # "Cookie": "ASP.NET_SessionId=rq5u0sy0us3dvnnckiidpm5r"
}


# 验证码判断
# def get_code(yzm):
#     img_code = pytesseract.image_to_string(Image.open(yzm))
#     print(img_code)
#     if len(img_code) == 4 and img_code.isalnum() is true:
#         print(img_code)
#         return img_code
#     else:
#         print('验证码不规范，重新识别')
#         get_code(yzm)

# 验证码页面
img_url = 'http://wgpc.wzsafety.gov.cn/ValidataImage.aspx'


# 登录程序
def login(_username, _password, _hang):
    # response = requests.get('http://wgpc.wzsafety.gov.cn/login_qygl.htm', headers=headers)
    # result = response.text
    # reg = r'<img class="ValidataImage" scr=*?'
    # print(result)
    # code_img_url = re.findall(reg, result)[0]
    # print(code_img_url)
    # response = requests.get(code_img_url, headers=headers)
    # code_img = response.content

    # 启用cook ie jar
    cookie = cookiejar.CookieJar()
    # 利用urllib.request库的HTTPCookieProcessor对象来创建cookie处理器,也就CookieHandler
    handler = request.HTTPCookieProcessor(cookie)
    # 通过CookieHandler创建opener
    opener = request.build_opener(handler)
    # 此处的open方法打开网页
    response = opener.open(img_url)
    # 打印cookie信息
    for item in cookie:
        cook_info = "ASP.NET_SessionId="+item.value
        # print('Name = %s' % item.name)
        # print('Value = %s' % item.value)
        # print(cook_info)
    # 带Cookie的头
    head = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0',
        'Cookie': cook_info
    }
    # print(head)
    # 发送请求
    res = requests.get(img_url, headers=head)
    # 获取图片信息
    img_data = res.content
    # print(res.content)
    # 把图片保存到电脑
    with open(r'E:/pythonsoft/yzm.jpg', mode='wb') as f:
       f.write(img_data)

    # fn = open('code.png','wb')
    # fn.write(code_img)
    # fn.close()
    # print(result)


    # 启动识别图片
    pytesseract.pytesseract.tesseract_cmd = 'c:\\Program Files\\Tesseract-OCR\\tesseract.exe'
    print('识别出的结果如下：')
    # 识别图片
    #img_code2 = get_code('yzm.jpg')
    img_code = pytesseract.image_to_string(Image.open('yzm.jpg'))

    print(img_code)
    # if len(img_code) == 4:
    #     if img_code.isalnum():
    #         print('验证码规范')
    #     else:
    #         login(username, password, row)
    # else:
    #     login(username, password, row)
    # if len(img_code) == 4 or img_code.isalnum():
    #     print('验证码不规范，重新获取')
    #     login(username, password, row)

    # 组织发送内容
    data = {
        'uid': _username,
        'pwd': md5(_password.encode("utf-8")).hexdigest(),
        'qx': 'undefined',
        # 'htmvalidatainfo': input('输入验证码：'),
        'htmvalidatainfo': img_code
    }
    # 发送登录内容
    res = requests.post('http://wgpc.wzsafety.gov.cn/Ajax/login_qydl.ashx', data=data, headers=head)
    # print(md5(password.encode("utf-8")).hexdigest())
    # print(res.url)
    # print(username)
    # print(md5(password.encode("utf-8")).hexdigest())
    # 打印返回内容
    print(res.text)
    # 登录正确后返回地址 http://wgpc.wzsafety.gov.cn/Commpany/HTMLPage52.htm
    if 'ID' in res.text:
        print('登录成功')
        id_info = json.loads(res.text)
        print(id_info['ID'])
        info(id_info['ID'], _username, id_info['企业名称'], _hang)
    else:
        print('登录失败，重新登录')
        login(_username, _password, _hang)


def info(_id, _name, qymc, hang):
    data = {
        'CID': _id
    }
    response = requests.post('http://wgpc.wzsafety.gov.cn/Commpany/Ajax/Handler104_2.ashx', data=data)
    print(response.text)

    workbook2 = xlwt.Workbook(encoding='utf-8')
    # 创建一个worksheet
    worksheet = workbook2.add_sheet('sheet1')
    # x = hang  # 在第二行开始写
    # y = 0  # 在第一列开始写
    xls = xlwt.Workbook()
    sheetname = xls.add_sheet('sheet1', cell_overwrite_ok=True)  # 生成excel的方法，声明excel
    sheetname.write(hang, 0, _id)  # x代表行，y代表列
    sheetname.write(hang, 1, _name)
    sheetname.write(hang, 2, qymc)# x代表行，y代表列
    if '本季度完成上报隐患' in response.text:
        sheetname.write(hang, 3, '本季度完成上报隐患')  # x代表行，y代表列
    else:
        sheetname.write(hang, 3, '未完成')  # x代表行，y代表列
        # print('未完成')
    #xls.save('E:/pythonsoft/result.xls')  # 保存
    # return response.text


# def write_excel_xls_append(path, value):
#     index = len(value)  # 获取需要写入数据的行数
#     workbook = xlrd.open_workbook(path)  # 打开工作簿
#     sheets = workbook.sheet_names()  # 获取工作簿中的所有表格
#     worksheet = workbook.sheet_by_name(sheets[0])  # 获取工作簿中所有表格中的的第一个表格
#     rows_old = worksheet.nrows  # 获取表格中已存在的数据的行数
#     new_workbook = copy(workbook)  # 将xlrd对象拷贝转化为xlwt对象
#     new_worksheet = new_workbook.get_sheet(0)  # 获取转化后工作簿中的第一个表格
#     for i in range(0, index):
#         for j in range(0, len(value[i])):
#             new_worksheet.write(i+rows_old, j, value[i][j])  # 追加写入数据，注意是从i+rows_old行开始写入
#     new_workbook.save(path)  # 保存工作簿
#     print("xls格式表格【追加】写入数据成功！")


if __name__ == '__main__':
    # 打开文件
    workbook = xlrd.open_workbook(r'E:/pythonsoft/qyidmm.xlsx')
    # 获取所有sheet
    #print(workbook.sheet_names())
    # 获取sheet2
    sheet_name = workbook.sheet_names()[0]
    #print(sheet_name)
    # 根据sheet索引或者名称获取sheet内容
    sheet = workbook.sheet_by_name(sheet_name)
    # sheet = workbook.sheet_by_name('Sheet1')
    # sheet的名称，行数，列数
    sheet_row = sheet.nrows
    # print(sheet_name, sheet_row, sheet.ncols)
    # print(sheet)
    # sheet的名称，行数，列数
    for row in range(sheet_row):
        # print(row)
        print(sheet.cell(row, 0).value)
        username = sheet.cell(row, 0).value
        password = sheet.cell(row, 0).value
        login(username, password, row)

        # abc = '1321wfwsf'
        # if abc.isalnum():
        #
        #     if len(abc) == 9:
        #         print('1')
        # else:
        #     print('2')
